package framework.server;

import java.util.Date;

import framework.Message;

/**
 * Mail contains a message, sender & schedule time.
 * 
 * @author  Orlin Tomov
 * @version 0.2
 */
public class Mail {

	/** the message sender */
	private String sender = null;
	/** the message contained in mail */
	private Message message = null;
	/** time when message scheduled to */
	private Date scheduled = null;

	/**
	 * create a mail
	 *
	 * @param	sender	the message sender service name
	 * @param	message	the message
	 */
	public Mail(String sender, Message message) {
		this.sender = sender;
		this.message = message;
	}

	/**
	 * create a mail
	 *
	 * @param	sender	the message sender service name
	 * @param	message	the message
	 * @param 	timeout	delay (in ms)
	 */
	public Mail(String sender, Message message, int timeout) {
		this.sender = sender;
		this.message = message;
		Date now = new Date();
		scheduled = new Date(now.getTime()+timeout);
	}

	/**
	 * extracts the message name
	 * 
	 * @return the message name
	 */
	public String getMessageName() {
		return message.getClass().getCanonicalName();
	}

	/**
	 * extracts the message sender service name
	 *
	 * @return the message sender service name
	 * @see framework.Message#getSender()
	 */
	public String getSender() {
		return sender;
	}

	/**
	 * extracts the message contained in mail
	 *
	 * @return the message contained in mail
	 */
	@SuppressWarnings("unchecked")
	public <M extends Message> M getMessage() {
		return (M) message;
	}

	/**
	 * extracts the time when message scheduled to
	 *
	 * @return time when message scheduled to
	 * @see framework.Message#getScheduled()
	 */
	public Date getScheduled() {
		return scheduled;
	}

	/**
	 * @see java.lang.Comparable#compareTo(java.lang.Object)
	 */
	@SuppressWarnings("unchecked")
	public int compareTo(Mail mail) {
		int result = 0;
		result = getSender().compareTo(mail.getSender());
		if (result != 0) {
			return result;
		}
		if (message == null) {
			if (mail.getMessage() != null) {
				return 1;
			}
		} else {
			if (mail.getMessage() == null) {
				return -1;
			}
			result = getMessageName().compareTo(mail.getMessageName());
			if (result != 0) {
				return result;
			}
			if (getMessage() instanceof Comparable<?>) {
				result = ((Comparable<Message>) getMessage()).compareTo(mail.getMessage());
			}
		}
		return result;
	}
}
